/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *MpmProjectTaskFeedbackController
 * 项目任务反馈
 *
 * 修改纪录
 * 2021-01-14 版本：1.0 lanjianwei 创建。
 * @version 版本：1.0
 * @author 作者：lanjianwei
 * 创建日期：2021-01-14
 */

package com.topscomm.mpm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectEntity;
import com.topscomm.mpm.service.impl.MpmProjectPlanService;
import com.topscomm.mpm.service.impl.MpmProjectService;
import com.topscomm.mpm.service.impl.MpmProjectTaskCloseService;
import com.topscomm.mpm.service.impl.MpmProjectTaskService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.tap.ITapService;

import java.util.*;
import java.util.stream.Collectors;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.mpm.controller.auto.MpmProjectTaskFeedbackControllerAuto;
import com.topscomm.mpm.pojo.MpmProjectTaskFeedbackEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.TapSystemConst.TapApprovalBillStateEnum;

/**
 * @author: lanjianwei
 * @date: 2021-01-14
 * @description:项目任务反馈Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/projectTaskFeedback")
public class MpmProjectTaskFeedbackController extends MpmProjectTaskFeedbackControllerAuto
		implements IMpmProjectTaskFeedbackController {
	@Autowired
	private MpmProjectService mpmProjectService;
	@Autowired
	private MpmProjectTaskCloseService mpmProjectTaskCloseService;
	@Autowired
	private MpmProjectPlanService mpmProjectPlanService;
	/**
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_taskid")) {
			String value = paraMap.get("qry_taskid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and taskid = '{0}'", value);
		}
		if (paraMap.containsKey("qry_taskfeedbackdetail")) {
			String value = paraMap.get("qry_taskfeedbackdetail").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and taskfeedbackdetail like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state in ({0})", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (paraMap.containsKey("qry_istaskfeedback")) {
			String value = paraMap.get("qry_istaskfeedback").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and istaskfeedback = '{0}' ", value);
		}
		/*
		 * if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限 {
		 * String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,
		 * "", this.getUserBean()); if (StringUtil.isEmpty(dataPession))//
		 * 默认权限只能看本人，部门负责人为自己的部门和下级部门的数据 { String deptcodes_header =
		 * ConvertUtil.convertToString(this.getUserBean().getUser().getValue(
		 * "deptcodes_header")); if (StringUtil.isEmpty(deptcodes_header)) sql.
		 * appendSingle(" and (usercode = '{0}' or deptcode ='{1}' or deptcode = '{2}' )"
		 * , this.getUserBean().getUser().getCode(),
		 * this.getUserBean().getDept().getCode(), this
		 * .getUserBean().getWorkDept().getCode()); else sql.
		 * appendSingle(" and (deptcode in ({0})  or usercode = '{1}' or deptcode ='{2}' or deptcode = '{3}' )"
		 * , deptcodes_header, this.getUserBean().getUser().getCode(), this
		 * .getUserBean().getDept().getCode(),
		 * this.getUserBean().getWorkDept().getCode()); } else// 使用数据权限 {
		 * sql.appendSingle(" and {0} ", dataPession); } }
		 */
		return sql.toString();
	}

	/**
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: lanjianwei
	 * @date: 2021-01-14
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目任务反馈申请! ", dataMap.get("dispdeptcode"), dataMap.get("username"),
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
		dataMap.put("maintitle", mailtitle.toString());
		// 保存和提交合并成一个按钮，后端提交时存入id
/*		String taskid = String.valueOf(paraMap.get("taskid"));
		String taskfeedbackdetail = (String) paraMap.get("taskfeedbackdetail");
		String taskschedule = String.valueOf(paraMap.get("taskschedule"));
		StringBufferProxy whereSql = new StringBufferProxy();
		whereSql.appendLineSingle("taskid='{0}' and taskfeedbackdetail = '{1}' and taskschedule = '{2}'", taskid,
				taskfeedbackdetail, taskschedule);
		List<MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntities = this.service
				.queryByWhere(whereSql.toString());
		if(mpmProjectTaskFeedbackEntities.size()>0) {
			long id = mpmProjectTaskFeedbackEntities.get(0).getId();
			dataMap.put("id", id);
		}else {
			throw new ServiceException("提交任务进度更新单据失败（无法获取任务更新单据的id），请联系管理员！");
		}*/

	}


	/**
	 * @author: wudaliang
	 * @date: 2021-03-12
	 * @param: paraMap
	 * @description: 删除已执行的任务时，删除对应的任务反馈
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@DeleteMapping({"/deletecasetask"})
	public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String ids = ConvertUtil.convertToString(paraMap.get("ids"));
			this.service.deleteByWhere(" taskid in (" + ids + ")");
			this.afterDelete(paraMap);
			return ResponseResult.ok("删除成功");
		} catch (Exception var3) {
			return this.handleControllerException(var3);
		}
	}


	/**
	 * @Title: submit
	 * @description: 先保存再提交
	 * @param paraMap
	 * @return
	 * @author: lanjianwei
	 * @date: 2021年2月1日上午10:32:57
	 * @modify:
	*/
	@PutMapping(value = "/submit")
	public ResponseResult<Object> submit(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
//			ResponseResult responseResult= this.insert(paraMap);
//			paraMap=(Map) responseResult.getResult();
			Map<String, Object> dataMap = paraMap;
			paraMap.put("submitdate", new Date());
			beforeSubmit(dataMap, paraMap);
			String mailTitle = "";
			if (dataMap.containsKey("maintitle")) {
				mailTitle = ConvertUtil.convertToString(dataMap.get("maintitle"));
			}
			MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity = this.service.queryById(ConvertUtil.convertToString(dataMap.get("id")));
			if (mpmProjectTaskFeedbackEntity == null) {
				Class<MpmProjectTaskFeedbackEntity> entityClass = this.entityClass;
				mpmProjectTaskFeedbackEntity = entityClass.newInstance();
			}
			// 处于审批中和已审批的单据不能再提交审批
			if (TapApprovalBillStateEnum.Approveing == ConvertUtil.convertToInt(mpmProjectTaskFeedbackEntity.getState())
					|| TapApprovalBillStateEnum.Approved == ConvertUtil.convertToInt(mpmProjectTaskFeedbackEntity.getState()))
				return ResponseResult.error("不是退回和开立的单据不能提交审批");
			for (Object key : dataMap.keySet()) {
				String tempKey = ConvertUtil.convertToString(key);
				mpmProjectTaskFeedbackEntity.setValue(tempKey, dataMap.get(key));
			}
			this.service.executeSubmit(mpmProjectTaskFeedbackEntity, mailTitle, this.getUserBean());
			dataMap = this.service.queryMapById(ConvertUtil.convertToString(dataMap.get("id")));
			// 增加前台待审批消息提醒
			afterSubmit(dataMap, paraMap);
			return ResponseResult.ok("提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	 * @Title: updateGap
	 * @description: 更新改进与反馈
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2022-06-07
	 * @modify:
	 */
	@PutMapping(value = "/updateGap")
	public ResponseResult<Object> updateGap(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			JSONArray jsonArray = (JSONArray) paraMap.get("feedbacklist");
			List<Map> feedbackList = JSONObject.parseArray(jsonArray.toJSONString(), Map.class);
			if (CollectionUtil.isEmpty(feedbackList)) {
				return ResponseResult.ok("保存成功");
			}
			// 获取该任务所有改进与反馈信息
			String taskid = ConvertUtil.convertToString(feedbackList.get(0).get("taskid"));
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" taskid = '{0}' and istaskfeedback = '0' ", taskid);
			List<MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntities = this.service.queryByWhere(sql.toString());
			Map<String, MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntityMap = mpmProjectTaskFeedbackEntities.stream().collect(Collectors.toMap(item -> ConvertUtil.convertToString(item.getId()), item -> item, (v1, v2) -> v1));
			if (ObjectUtil.isEmpty(mpmProjectTaskFeedbackEntityMap)) {
				return ResponseResult.ok("保存成功");
			}
			// 遍历feedbacklist，变动的改进与反馈需要进行更新并发送APP消息
			List<Map<String, Object>> updateBatchMap = new ArrayList<>();
			for (Map<String, Object> feedbackMap : feedbackList) {
				// 任务反馈内容不需要更新
				if ("1".equals(feedbackMap.get("istaskfeedback"))) {
					continue;
				}
				// 如果修改了差距与改进的内容，需要更新
				if (!this.judgeGapSame(feedbackMap, mpmProjectTaskFeedbackEntityMap)) {
					updateBatchMap.add(feedbackMap);
				}
			}
			if (!CollectionUtil.isEmpty(updateBatchMap)) {
				// 更新差距与改进内容
				this.service.updateBatchMap(updateBatchMap);
				// 向任务责任人发送消息
				MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity = new MpmProjectTaskFeedbackEntity();
				this.service.sendMessageGap(mpmProjectTaskFeedbackEntity.convertFromMap(updateBatchMap.get(0)));
			}
			return ResponseResult.ok("保存成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	 * @description: 重写datacodelist
	 * @param paraMap
	 * @return
	 * @author: houyuhang
	 * @date: 2022-06-07
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/dataCodeList")
	public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
		Map<String, Object> codeMap = (Map<String, Object>) super.dataCodeList(paraMap).getResult();
		List<Map<String, Object>> feedbackYesNoList = datacodeCache.getCodeListMap("MpmFeedbackYesNo", "", "sortcode");
		codeMap.put("feedbackyesnolist", feedbackYesNoList);
		List<Map<String, Object>> taskupdatefreList = datacodeCache.getCodeListMap("MpmTaskUpdateFre", "", "sortcode");
		codeMap.put("taskupdatefreList", taskupdatefreList);
		return ResponseResult.ok(codeMap);
	}
	/**
	 * @description: 判断该条差距与改进是否修改
	 * @return
	 * @author: houyuhang
	 * @date: 2022-06-15
	 * @modify:
	 */
	public Boolean judgeGapSame(Map<String, Object> feedbackMap, Map<String, MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntityMap) {
		MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity = mpmProjectTaskFeedbackEntityMap.get(ConvertUtil.convertToString(feedbackMap.get("id")));
		return feedbackMap.get("gapanalysis").equals(mpmProjectTaskFeedbackEntity.getGapanalysis()) && feedbackMap.get("managerplan").equals(mpmProjectTaskFeedbackEntity.getManagerplan());
	}
	/**
	 * @description: 获取附件是否能够查看的权限
	 * @return
	 * @author: houyuhang
	 * @date: 2022-11-23
	 * @modify:
	 */
	@GetMapping("/queryCanAttachment")
	public ResponseResult<Object> queryCanAttachment(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" enabled = 1 and projectcode = '{0}' ", ConvertUtil.convertToString(paraMap.get("qry_projectcode")));
			MpmProjectEntity mpmProjectEntity = mpmProjectService.queryObjectByWhere(sql.toString());
			if (ObjectUtil.isEmpty(mpmProjectEntity)) {
				return ResponseResult.ok(false);
			}
			String usercode = this.getUserBean().getUser().getCode();
			String projectmanagercode = mpmProjectEntity.getProjectmanagercode();
			String ownercode = mpmProjectEntity.getOwnercode();
			if (MpmSystemConst.BidUserCode.contains("," + usercode + ",") || projectmanagercode.equals(usercode) || ownercode.equals(usercode)) {
				return ResponseResult.ok(true);
			}
			return ResponseResult.ok(false);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	/**
	 * @description: 获取任务反馈、差距与改进、任务关闭信息
	 * @return
	 * @author: houyuhang
	 * @date: 2023-01-13
	 * @modify:
	 */
	@GetMapping("/allList")
	public ResponseResult<Object> allList(@RequestParam(required = false) Map<String, Object> paraMap) {
		List<Map<String, Object>> resultList = new ArrayList<>();
		// 获取任务关闭信息
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled = 1 and taskid = '{0}' ", ConvertUtil.convertToString(paraMap.get("qry_taskid")));
		if (paraMap.containsKey("qry_state")) {
			sql.appendSingle(" and state in ({0}) ", ConvertUtil.convertToString(paraMap.get("qry_state")));
		}
		if (paraMap.containsKey("sidx") && paraMap.containsKey("sord")) {
			sql.appendSingle(" order by {0} {1}, id asc ", ConvertUtil.convertToString(paraMap.get("sidx")), ConvertUtil.convertToString(paraMap.get("sord")));
		}
		List<Map<String, Object>> taskCloseList = mpmProjectTaskCloseService.queryMapByWhere(sql.toString());
		taskCloseList.forEach(item -> {
			item.put("istaskclose", "1");
		});
		resultList.addAll(taskCloseList);
		// 获取任务反馈、差距与改进信息
		resultList.addAll(this.service.queryMapByWhere(sql.toString()));
		return ResponseResult.ok(resultList);
	}
	/**
	 * @description: 判断任务反馈对应的项目是否为A级省总项目
	 * @return
	 * @author: houyuhang
	 * @date: 2023-03-13
	 * @modify:
	 */
	@GetMapping("/queryALevelManager")
	public ResponseResult<Object> queryALevelManager(@RequestParam(required = false) Map<String, Object> paraMap) {
		Map<String, Object> resMap = new HashMap<>();
		boolean res = mpmProjectPlanService.judgeProvinceManager(ConvertUtil.convertToString(paraMap.get("projectcode")));
		resMap.put("aLevelManager", res);
		return ResponseResult.ok(resMap);
	}
}
